<template>
  <div class="user-menu-container">
    <el-dropdown
      trigger="click"
      placement="bottom-end"
      popper-class="custom-user-menu"
    >
      <span class="user-info-wrapper">
        <div class="avatar-content">
          <el-avatar
            :size="36"
            :src="userInfo.avatar"
            :style="{
              backgroundColor: userInfo.avatar ? 'transparent' : '#4a90e2',
              fontSize: '16px',
            }"
          >
            {{ avatarInitial }}
          </el-avatar>
        </div>
        <div class="user-meta">
          <span class="username">{{ displayName }}</span>
          <span class="user-role">{{ userRole }}</span>
        </div>
        <i class="menu-indicator el-icon-arrow-down"></i>
      </span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="navigateTo('/profile')">
            <i class="el-icon-user-solid"></i>
            <span>个人中心</span>
          </el-dropdown-item>

          <!-- 租客菜单 -->
          <template v-if="userRole === '租客'">
            <el-dropdown-item divided @click="FavoritesList()">
              <i class="el-icon-collection"></i>
              <span>收藏列表</span>
            </el-dropdown-item>
          </template>

          <!-- 房东菜单 -->
          <template v-else-if="userRole === '房东'">
            <el-dropdown-item divided @click="AddHouse()">
              <i class="el-icon-document"></i>
              <span>发布房源</span>
            </el-dropdown-item>
            <el-dropdown-item @click="Houselist()">
              <i class="el-icon-office-building"></i>
              <span>房源管理</span>
            </el-dropdown-item>
          </template>

          <!-- 公共退出项 -->
          <el-dropdown-item divided @click="MyFeedback()">
            <i class="el-icon-switch-button"></i>
            <span>我的反馈</span>
          </el-dropdown-item>
          <el-dropdown-item @click="Order()">
            <i class="el-icon-document"></i>
            <span>订单管理</span>
          </el-dropdown-item>
          <el-dropdown-item @click="UpdatePwd">
            <i class="el-icon-switch-button"></i>
            <span>修改密码</span>
          </el-dropdown-item>
          <el-dropdown-item @click="handleLogout">
            <i class="el-icon-switch-button"></i>
            <span>安全退出</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup>
// 添加必要的Vue API导入
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";

const router = useRouter();
const userStore = useUserStore();

// 确保所有响应式变量正确初始化
const menuVisible = ref(false);
const isMobile = ref(false);

// 用户信息计算属性增强容错处理
const userInfo = computed(() => userStore.userInfo || {});

const roles = computed(() => userInfo.value.roles || []);

const avatarInitial = computed(() => {
  const name = userInfo.value.nickname;
  return name.charAt(0).toUpperCase() || "?";
});

const displayName = computed(() => {
  return userInfo.value.nickname || userInfo.value.name || "新用户";
});

// 角色显示转换逻辑
const userRole = computed(() => {
  const roleMapping = {
    ROLE_Tenant: "租客",
    ROLE_Landlord: "房东",
  };

  const mainRole = roles.value[0].name;
  return roleMapping[mainRole] || mainRole.replace("ROLE_", "");
});

// 窗口尺寸监听逻辑
const handleResize = () => {
  isMobile.value = window.innerWidth < 768;
};

onMounted(() => {
  window.addEventListener("resize", handleResize);
  handleResize();

  if (!userStore.userInfo?.id) {
    userStore.fetchUserInfo().catch(() => {
      console.warn("用户信息自动获取失败");
    });
  }
});

onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});

// 增强导航方法
const navigateTo = (path) => {
  router.push(path);
  menuVisible.value = false;
};

// 安全退出逻辑
const handleLogout = () => {
  // 清除所有前端状态
  userStore.clearUserInfo();

  // 特别注意清除主 token
  localStorage.removeItem("token");

  // 强制刷新并跳转
  window.location.href = "/login";

  // 双重保险路由跳转
  router.replace("/login");
};

const AddHouse = () => {
  router.push("/addHouse");
};

const FavoritesList = () => {
  router.push("/favoritesList");
};

const Houselist = () => {
  router.push("/Houselist");
};

const UpdatePwd = () => {
  router.push("/updatePwd");
};

const Order = () => {
  router.push("/order");
};
const MyFeedback = () => {
  router.push("/myFeedback");
};
</script>

<style scoped>
/* 容器定位 */
.user-menu-container {
  position: relative;
  margin-right: 24px;
}

/* 触发区域样式 */
.user-info-wrapper {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  background: rgba(255, 255, 255, 0.1);

  &:hover {
    background: rgba(255, 255, 255, 0.2);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.avatar-content {
  margin-right: 12px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  margin-right: 8px;
}

.username {
  font-size: 14px;
  color: #2c3e50;
  font-weight: 500;
  line-height: 1.2;
}

.user-role {
  font-size: 12px;
  color: #7f8c8d;
  margin-top: 2px;
}

.menu-indicator {
  font-size: 12px;
  color: #95a5a6;
  transition: transform 0.3s;
  margin-left: 4px;

  &.rotate {
    transform: rotate(180deg);
  }
}

/* 下拉菜单样式 */
:deep(.custom-user-menu) {
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2) !important;
  border: none !important;
  border-radius: 12px !important;
  padding: 16px 0 !important;
  background-color: #fff !important;

  .el-dropdown-menu__item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 24px;
    font-size: 14px;
    color: #2c3e50;
    transition: all 0.2s;
    cursor: pointer;

    &:hover {
      background: #f0f8ff;
      color: #3498db;

      i,
      span {
        color: #3498db;
      }
    }

    i {
      font-size: 18px;
      margin-right: 16px;
      color: #7f8c8d;
    }

    span {
      flex-grow: 1;
      text-align: center;
    }
  }

  .el-dropdown-menu__item--divided::before {
    left: 24px;
    right: 24px;
  }
}
</style>
